//
//  PipeiViewController.m
//  zhihuiguanjia
//
//  Created by apple on 15/12/29.
//  Copyright © 2015年 MyCompany. All rights reserved.
//
//
#import "PipeiViewController.h"
#import "LoginViewController.h"
#import "JKCountDownButton.h"
#import "CommonPickerViewController.h"
#import "SDWebImageManager.h"
#import "UIImageView+WebCache.h"
#import "CameraAlbum.h"

@interface PipeiViewController ()<CommonPickerDelegate,UIActionSheetDelegate,CameraAlbumDelegate>

@property (nonatomic, strong) NSArray *_cityList;
@property (nonatomic, strong) UIButton *back;
@property (nonatomic, strong) CommonPickerViewController *picker;
@property (nonatomic, strong) NetworkManager *networkManager;

@property (weak, nonatomic) IBOutlet UILabel *xiaoquLbl;
@property (weak, nonatomic) IBOutlet UILabel *zhuhuIdLbl;
@property (weak, nonatomic) IBOutlet UILabel *userIdLbl;

@property (nonatomic, strong) NSMutableArray *componentData;
@property (nonatomic, strong) NSMutableArray *cityIdData;
@property (nonatomic, strong) NSMutableArray *xiaoquData;
@property (nonatomic, strong) NSMutableArray *xiaoquIdData;
@property (nonatomic, strong) NSString *city_id;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, assign) CGRect contentPreFrame;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (nonatomic, strong) CameraAlbum *cameraAlbum;
@property (nonatomic, strong) NSString *imageStr;

@end

@implementation PipeiViewController
@synthesize check2 = _check2;

- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];
    [super viewDidLoad];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.delegate = self;
    
    CGRect frame = self.contentView.frame;
    self.contentPreFrame = frame;
    UserInfo *user = [UserInfo instance];
    
    if([user.info objectForKey:@"touxiang"]){
        NSString *image1Str = [NSString stringWithFormat:@"%@%@",SERVER_PATH,[user.info valueForKey:@"touxiang"]];
        NSURL *url1 = [NSURL URLWithString:image1Str];
        [_touxiangImage sd_setImageWithURL:url1];
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        [manager downloadImageWithURL:url1 options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        }];
    } else {
        NSString *image1Str = [NSString stringWithFormat:@"%@%@",SERVER_PATH,@"home_photo.png"];
        NSURL *url1 = [NSURL URLWithString:image1Str];
        [_touxiangImage sd_setImageWithURL:url1];
    }
}

//点击拍照按钮
- (IBAction)takePhotoAction:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照",@"从相册选择", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
    
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [self openSystemCamera];
    }
    else if (buttonIndex==1) {
        [self openSystemImageLib];
    }
}

#pragma mark - Camera
- (void)openSystemCamera{
    if (self.cameraAlbum==nil) {
        self.cameraAlbum = [CameraAlbum instance];
        self.cameraAlbum.delegate = self;
    }
    [self.cameraAlbum openCameraInTargetViewController:self];
}

- (void)openSystemImageLib{
    if (self.cameraAlbum==nil) {
        self.cameraAlbum = [CameraAlbum instance];
        self.cameraAlbum.delegate = self;
    }
    [self.cameraAlbum openPhotoLibraryInTargetViewController:self];
}

#pragma mark - CameraAlbumDelegate
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this newcontext, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (UIImage *)setTheSeletedImage:(UIImage *)image
{//压缩图片
    UIImage *returnImage = [[UIImage alloc]init];
    //h=720, w=640
    if (image.size.height > image.size.width) {
        if (image.size.height < 640) {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)];
        }else{
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width*640/image.size.height, 640)];
        }
        
    } else {
        if (image.size.width < 640) {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)];
        }else {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(640, image.size.height*640/image.size.width)];
        }
    }
    return returnImage;
    //压缩后图片
}

-(void)getSavedImage:(UIImage*)image {
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    long interval = (long)timeInterval;
    
    UserInfo *user = [UserInfo instance];
    
    NSString *user_id =[user.info objectForKey:@"user_id"];
    NSString *wtpc = [NSString stringWithFormat:@"%ld",interval];
    NSString *path = [NSString stringWithFormat:@"%@",wtpc];
    
    NSMutableArray *fileList = [NSMutableArray array];
    NSMutableArray *fileNameList = [NSMutableArray array];
    NSData *imgData = nil;
    NSString *imagetype = @".jpeg";
    if (image != nil) {
        if (UIImagePNGRepresentation(image) == nil) {
            imgData = UIImageJPEGRepresentation(image, 1);
            imagetype = @".jpeg";
        } else {
            imgData = UIImagePNGRepresentation(image);
            imagetype = @".png";
        }
    }
    _imageStr = [NSString stringWithFormat:@"%@/%@%@",path,@"1",imagetype];
    [fileNameList addObject:_imageStr];
    NSDictionary *fileDict = [NSDictionary dictionaryWithObjectsAndKeys:
                              imgData,@"path",
                              _imageStr,@"name", nil];
    [fileList addObject:fileDict];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_100.png"]];   // 保存文件的名称
    [UIImagePNGRepresentation(image)writeToFile: filePath    atomically:YES];
    NSString *fileNameListStr = [fileNameList componentsJoinedByString:@","];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           fileList,@"FILE",
                           fileNameListStr,@"touxiang",
                           user_id,@"user_id",
                           path,@"md_input_path", nil];
    [self.networkManager requestWithMethod:updateUserinfo parameter:param delegate:self];
    
    [self.HUD show:YES];
}



- (IBAction)showInfo:(id)sender {
    if([self.xiaoquLbl.text isEqualToString:@"暂无匹配，请与物业联系"]){
        
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:self.xiaoquLbl.text
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
}

- (IBAction)next:(id)sender {
    if(_check2 != nil && !_check2.checked){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请匹配房屋信息"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    else {
        if (self.networkManager == nil) {
            self.networkManager = [[NetworkManager alloc] init];
        }
        
        
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               self.zhuhuIdLbl.text,@"zhuhu_id", self.userIdLbl.text,@"user_id",nil];
        [self.networkManager requestWithMethod:pipei parameter:param delegate:self];
        [self.HUD show:YES];
        
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           _phone,@"phone", nil];
    [self.networkManager requestWithMethod:getZhuhuListByPhone parameter:param delegate:self];
    [self.HUD show:YES];
}


- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    if (methodId == getZhuhuListByPhone) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            NSString * vercode = [data objectForKeyOrNil:@"resultinfo"];
            self.userIdLbl.text = [[data objectForKeyOrNil:@"userId"] stringValue];
            if([result isEqualToString:@"000"]){
                NSArray *results = [data objectForKeyOrNil:@"zhuhuList"];
                NSString *stringAll =@"";
                NSString *zhuhuidAll =@"";
                if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    for(id obj in results){
                        NSString *louStr = [[obj objectForKeyOrNil:@"lou"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        NSString *xiaoquStr = [[obj objectForKeyOrNil:@"xiaoqu"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        NSString *menpaiStr = [[obj objectForKeyOrNil:@"menpai"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        
                        stringAll =  [stringAll stringByAppendingFormat:@"%@/%@/%@\n",xiaoquStr, louStr, menpaiStr ];
                        zhuhuidAll = [zhuhuidAll stringByAppendingFormat:@"%@,",[[obj objectForKeyOrNil:@"zhuhuId" ] stringValue] ] ;
                    }
                    self.xiaoquLbl.text = stringAll;
                    self.zhuhuIdLbl.text = zhuhuidAll;
                    _check2 = [[QCheckBox alloc] initWithDelegate:self];
                    _check2.frame = CGRectMake(280, 235, 100, 50);
                    [_check2 setTitle:@"" forState:UIControlStateNormal];
                    [_check2 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                    [_check2.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0f]];
                    [self.view addSubview:_check2];
                }
            }
        }
        
    } else if (methodId == pipei) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
//            NSString * vercode = [data objectForKeyOrNil:@"resultinfo"];
            if([result isEqualToString:@"000"]){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"匹配成功！"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
                
                LoginViewController *problemVC = (LoginViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
                CATransition* transition = [CATransition animation];
                transition.type = kCATransitionPush;//可更改为其他方式
                transition.subtype = kCATransitionFromRight;//可更改为其他方式
                [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
                [self.navigationController pushViewController:problemVC animated:NO];
            }
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"数据获取失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (BOOL) isBlankString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

@end